using System;

namespace PentaBiz.Collections
{
    /// <summary>
    /// Provides object pool wrapped item.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class ObjectPoolItem<T> : IDisposable
    {
        private bool _disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectPoolItem{T}" /> class.
        /// </summary>
        /// <param name="pool">The pool.</param>
        /// <param name="instance">The instance.</param>
        internal ObjectPoolItem(ObjectPool<T> pool, T instance)
        {
            Pool = pool;
            Instance = instance;
        }

        /// <summary>
        /// Gets the object pool.
        /// </summary>
        /// <value>
        /// The pool.
        /// </value>
        public ObjectPool<T> Pool { get; private set; }

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        public T Instance { get; private set; }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        ~ObjectPoolItem()
        {
            Dispose(false);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                Pool.PutObject(Instance);

                _disposed = true;
            }
        }


       
        public static implicit operator T(ObjectPoolItem<T> poolItem)
        {
            return poolItem.Instance;
        }
    }
}